package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.constants.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description 即时消息Service
 * @date 2021/10/30
 */
@Service
public class MessagesService {
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private AnnouncementApi announcementApi;
    @DubboReference
    private MovementApi movementApi;
    /**
     * 环信-根据环信id查询用户信息
     * @param huanxinId
     * @return
     */
    public UserInfoVO userInfo(String huanxinId) {
        User user = userApi.findByHuanXinId(huanxinId);
        UserInfo userInfo = userInfoApi.selectById(user.getId());
        return UserInfoVO.init(userInfo);
    }

    /**
     * 消息-添加联系人
     * @param friendId
     */
    public void addContacts(Long friendId) {
        //注册环信好友关系
        Long userId = UserHolder.getUserId();
        String username1 = Constants.HX_USER_PREFIX + userId;
        String username2 = Constants.HX_USER_PREFIX + friendId;
        Boolean addContact = huanXinTemplate.addContact(username1, username2);
        if (!addContact) {
            throw new BusinessException(ErrorResult.error());
        }
        //添加Friend数据库表中的好友关系
        friendApi.saveContacts(userId, friendId);
    }

    /**
     * 消息-查询联系人列表
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult getContacts(Integer page, Integer pagesize, String keyword) {
        Long userId = UserHolder.getUserId();
        List<Friend> friends = friendApi.getContacts(userId, page, pagesize);
        if (CollUtil.isEmpty(friends)) {
            return new PageResult();
        }
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.selectByIdsAndCondition(friendIds, userInfo);
        List<ContactVO> contactVOs = new ArrayList<>();
        for (Friend friend : friends) {
            UserInfo info = map.get(friend.getFriendId());
            if (ObjectUtil.isNotEmpty(info)) {
                contactVOs.add(ContactVO.init(info));
            }
        }
        return new PageResult(page, pagesize, 0, contactVOs);
    }

    /**
     * 消息-公告列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getAnnouncements(Integer page, Integer pagesize) {
        IPage<Announcement> iPage = announcementApi.getAnnouncements(page, pagesize);
        List<Announcement> announcements = iPage.getRecords();
        List<AnnouncementVO> announcementVOs = new ArrayList<>();
        if (CollUtil.isNotEmpty(announcements)) {
            for (Announcement announcement : announcements) {
                announcementVOs.add(AnnouncementVO.init(announcement));
            }
        }
        Integer counts = Integer.valueOf(String.valueOf(iPage.getTotal()));
        return new PageResult(page, pagesize, counts, announcementVOs);
    }

    /**
     * 消息-点赞(likes)/评论(comments)/喜欢(loves)列表
     * @param commentType --》 LIKE/COMMENT/LOVE
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getList(CommentType commentType, Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        List<Comment> comments = movementApi.getList(userId, commentType, page, pagesize);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.selectByIdsAndCondition(userIds, null);
        List<CommentVO> commentVOs = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (ObjectUtil.isNotEmpty(userInfo)) {
                if (userInfo.getId().equals(userId)) {
                    continue;
                }
                commentVOs.add(CommentVO.init(userInfo, comment));
            }
        }
        return new PageResult(page, pagesize, 0, commentVOs);
    }
}
